var rkshzcstock = {
    fillData:function () {
        $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm':'cd'}, function (cddata) {
            $.post($.webPath() + '/base/sjzdsy/get_sjzdz', {'bm':'jzfs'}, function (data) {
                fillHtmxByCgd($.webPath() + '/kcgl/rksh/rksh_rkmx?rksh.id=' + $("[name='rksh.id']").val() || '', cddata, data);
            })
        });
    }
}

//采购单明细
function fillHtmxByCgd(href, cdOptions, fsOptions) {
    $("#rksh_zcrk_mx").edatagrid({
        url:href,
        fitColumns:false,
        singleSelect:true,
        fit:false,
        height:400,
        checkOnSelect:false,
        selectOnCheck:false,
        rownumbers:true,
        toolbar:"#rksh_cgdmx_toolbar",
        frozenColumns:[
            [
                {field:'wzgg.oldcode', title:'老物资编码', align:'center', hidden:true},
                {field:'wzgg.code', title:'新物资编码', align:'center', width:100, rowspan:2},
                {field:'wzgg.name', title:'物资名称', align:'center', width:70, rowspan:2},
                {field:'wzgg.ggxh', title:'规格型号', align:'center', width:70, rowspan:2},
                {field:'wzgg.th', title:'图号', align:'center', hidden:true},
                {field:'cd.z', title:'产地', align:'center', width:40, rowspan:2},
                {field:'jzfs.id', align:'center', formatter:function (value) {
                    for (var i = 0; i < fsOptions.length; i++) {
                        if (fsOptions[i].id == value) return fsOptions[i].z;
                    }
                    return value;
                }, title:'记重方式', width:50, align:'center', rowspan:2},
                {field:'dlkh.qc', title:'代理客户', align:'center', width:100, rowspan:2}
            ]
        ],
        columns:[
            [
                {title:'申报', colspan:2},
                {title:'已入库', colspan:2},
                {title:'到货', colspan:2},
                {field:'kh.id', title:'卡号ID', hidden:true},
                {field:'kh.khbm', title:'卡号编码', align:'center', hidden:true},
                {field:'hsj', title:'含税价', align:'right', width:170, rowspan:2,
                    formatter:function (value) {
                        var val = formatJeForHtml(value);
                        return val;
                    }},
                {field:'bhsj', title:'不含税价', align:'right', width:170, rowspan:2,
                    formatter:function (value) {
                        var val = formatJeForHtml(value);
                        return val;
                    }}
            ],
            [
                {field:'js', title:'件数', align:'right', precision:4, width:100},
                {field:'sbsl', title:'重量', align:'right', precision:4, width:150,
                    formatter:function (value) {
                        var val = formatSlForHtml(value);
                        return val;
                    }},
                {field:'yrjs', title:'件数', align:'right', precision:4, width:100},
                {field:'yrsl', title:'重量', align:'right', precision:4, width:150,
                    formatter:function (value) {
                        var val = formatSlForHtml(value);
                        return val;
                    }},
                {field:'rkjs', title:'件数', align:'right', width:100, editor:{type:'numberbox'}},
                {field:'rksl', title:'重量', align:'right', width:200, editor:{type:'numberbox', options:{min:0, precision:4}},
                    formatter:function (value) {
                        var val = formatSlForHtml(value);
                        return val;
                    }}
            ]
        ],
        loadFilter:function (data) {
            $.each(data.rows, function () {
                this['rksl'] = this.sssl;
                this['rkjs'] = this.ssjs;
            })
            return data;
        },
        onSelect:function (rowIndex, rowData) {
            $("#rksh_zcrk_mx").edatagrid('editRow', rowIndex);
            var editors = $("#rksh_zcrk_mx").datagrid('getEditors', rowIndex);
            if (editors.length == 0)
                return;
            var js = editors[0];
            var sl = editors[1];
            $(js.target).unbind('blur').bind('blur', function () {
                $(js.target).numberbox('setValue', $(js.target).val());
                var cdVal = rowData["cd.id"];
                if (cdVal != "" && cdVal) {
                    var selected = $('#rksh_zcrk_mx').datagrid('getSelected');
                    $.post($.webPath() + '/cggl/cgdgl/get_jz', {'ggId':selected['wzgg.id'], cdId:rowData["cd.id"]}, function (data) {
                        var obj = eval('(' + data + ')');
                        if (obj.jz && obj.jz != "") {
                            $(sl.target).numberbox('setValue', parseFloat(obj.jz) * $(js.target).numberbox('getValue'));
                        } else {
                            $(sl.target).numberbox('setValue', 0);
                            $(sl.target).select();
                        }
                    })
                }
            })
        }
    })

}

$(function () {
    rkshzcstock.fillData();

    setTimeout(function () {
        $('#rksh_dhd_tabs').tabs('select', "入库明细");
    }, 100);

    //全部入库按钮触发
    $('#btn_rkshMx_allSave_dhd').click(function () {
        rksh.win_rksh.mask();
        $('#rksh_zcrk_mx').edatagrid('acceptChanges');
        var rk_datas = $('#rksh_zcrk_mx').edatagrid('getData');
        var flag = true;
        $.each(rk_datas.rows, function (i, val) {
            var rkskSum = 0;
            var rkjsSum = 0;
            var ssslSum = 0;
            var ssjsSum = 0;
            var sbjsSum = 0;
            var sbslSum = 0;
            $.each(rk_datas.rows, function (j, v) {
                if (val["mx.id"] == v["mx.id"]) {
                    ssslSum = parseFloat(isNaN(val.sssl) ? 0 : val.sssl);
                    ssjsSum = parseFloat(isNaN(val.ssjs) ? 0 : val.ssjs);
                    sbjsSum += parseFloat(isNaN(v.js) ? 0 : v.js);
                    sbslSum += parseFloat(isNaN(v.sbsl) ? 0 : v.sbsl);
                    if (val.rksl)
                        rkskSum += parseFloat(isNaN(v.rksl) ? 0 : v.rksl);
                    if (val.rkjs)
                        rkjsSum += parseFloat(isNaN(v.rkjs) ? 0 : v.rkjs);
                }
            })
            if (parseFloat(sbjsSum) >= parseFloat(ssjsSum)) {
                if ((parseFloat(val.rkjs) + parseFloat(val.yrjs)) > val.js) {
                    $.messager.alert("提示", "物资：" + val["wzgg.name"] + "  规格：" + val["wzgg.ggxh"] + "  产地：" + val["cd.z"] + "  分配数量" + (parseFloat(val.rkjs) + parseFloat(val.yrjs)) + "大于申报件数" + val.js + "无法入库!请重新分配。", "waring");
                    rksh.win_rksh.mask('hide');
                    flag = false;
                    return false;
                }
            } else {
                if ((parseFloat(val.rkjs) + parseFloat(val.yrjs)) > val.js) {
                    $.messager.alert("提示", "物资：" + val["wzgg.name"] + "  规格：" + val["wzgg.ggxh"] + "  产地：" + val["cd.z"] + "  分配数量" + (parseFloat(val.rkjs) + parseFloat(val.yrjs)) + "大于申报件数" + val.js + "无法入库!请重新分配。", "waring");
                    rksh.win_rksh.mask('hide');
                    flag = false;
                    return false;
                }
                //val.rkjs = parseFloat(val.js) - parseFloat(val.yrjs);
            }
            if (parseFloat(sbslSum) >= parseFloat(ssslSum)) {
                if ((parseFloat(val.rksl) + parseFloat(val.yrsl)) > val.sbsl) {
                    $.messager.alert("提示", "物资：" + val["wzgg.name"] + "  规格：" + val["wzgg.ggxh"] + "  产地：" + val["cd.z"] + "  分配数量" + (parseFloat(val.rksl) + parseFloat(val.yrsl)) + "大于申报数量" + val.sbsl + "无法入库!请重新分配。", "waring");
                    rksh.win_rksh.mask('hide');
                    flag = false;
                    return false;
                }
            } else {
                if ((parseFloat(val.rksl) + parseFloat(val.yrsl)) > val.sbsl) {
                    $.messager.alert("提示", "物资：" + val["wzgg.name"] + "  规格：" + val["wzgg.ggxh"] + "  产地：" + val["cd.z"] + "  分配数量" + (parseFloat(val.rksl) + parseFloat(val.yrsl)) + "大于申报数量" + val.sbsl + "无法入库!请重新分配。", "waring");
                    rksh.win_rksh.mask('hide');
                    flag = false;
                    return false;
                }
                //val.rksl = parseFloat(val.sbsl) - parseFloat(val.yrsl);
            }
            if (parseFloat(rkskSum) > parseFloat(ssslSum)) {
                $.messager.alert("提示", "物资：" + val["wzgg.name"] + "  规格：" + val["wzgg.ggxh"] + "  产地：" + val["cd.z"] + "  到货重量" + rkskSum.toFixed(4) + "大于仓储返回重量" + ssslSum.toFixed(4) + "无法入库!请重新分配。", "waring");
                rksh.win_rksh.mask('hide');
                flag = false;
                return false;
            } else if (parseFloat(rkjsSum) > parseFloat(ssjsSum)) {
                $.messager.alert("提示", "物资：" + val["wzgg.name"] + "  规格：" + val["wzgg.ggxh"] + "  产地：" + val["cd.z"] + "到货件数" + rkjsSum.toFixed(4) + "大于仓储返回计件数" + ssjsSum.toFixed(4) + "无法入库!请重新分配。", "waring");
                rksh.win_rksh.mask('hide');
                flag = false;
                return false;
            }
        })
        if (flag) {
            rksh_stock();
        }
    });

    $("#rksh-uploadify").upload('rksh-fileQueue', {
        onUploadSuccess: function (file, data, response) {
            var obj = eval('(' + data + ')');
            $("#rksh-fileQueue .data").remove();
            $("#rksh-fileQueue .uploadify-progress").fadeOut(500, function () {
                $(this).remove();
            });
            $("#" + file.id).append("<input type='hidden' id='rksh-file" + obj.fileId + "' name='rksh.fjList.id' value='" + obj.fileId + "'/>");
            $("#" + file.id + " .cancel a").bind('click', function () {
                $(this).attr('href', 'javascript:void(0)');
                deleteFj(obj.fileId, file.id);
            });
        }
    });

})

//全部入库调用方法
function rksh_stock() {
    $("#rksh_zcrk_mx").edatagrid('saveRow');
    $("#rksh_cgd_Form").form('submit', {
        url:$.webPath() + "/kcgl/rksh/stock_rksh",
        onSubmit:function (param) {
            $("#rksh-fileQueue input[name='rksh.fjList.id']").each(function(i){
                param['rksh.fjList['+i+'].id'] = $(this).val();
            });
            var data = $('#rksh_zcrk_mx').edatagrid("getData");
            if (!data.rows.length) {
                $('#rksh_cgd_Form').tabs('select', "采购明细");
                $.messager.alert("提示", "采购明细需要填写!", "waring");
                rksh.win_rksh.mask('hide');
                return false;
            }
            var arrayPrefix = 'rksh.cgdmxList';
            //物资计划明细
            var paramString = "{";
            //物资计划明细
            var sum = 0;
            for (var i = 0; i < data.rows.length; i++) {
                var temp = parseFloat(data.rows[i]['rksl']);
                temp = isNaN(temp) ? 0 : temp;
                sum += temp;


                var objectString = $.toJSONStringSubPrefix(data.rows[i], arrayPrefix + "[" + i + "].",
                    [
                        ['mx.id', 'id'],
                        ['wzgg.id', 'gg.id'],
                        'cd.id',
                        'jzfs.id',
                        'hsj',
                        'bhsj',
                        'sku',
                        'bz',
                        'sbsl',
                        'js',
                        'rksl',
                        'rkjs',
                        'ssjs',
                        'sssl',
                        'mxh',
                        ['kh.id', 'kh.id'],
                        ['jhmx.id', 'kh.bgjhmx.id']
                    ]);
                paramString = paramString + objectString.substring(1, objectString.length - 1) + ",";
            }
            if (sum == 0) {
                $.messager.alert('提示', '入库总重量不能为0或者该计划已分配量等于申报数量无法再次入库!', 'info');
                rksh.win_rksh.mask('hide');
                return false;
            } else {
                if (data.rows && data.rows.length > 0)
                    paramString = paramString.substring(0, paramString.length - 1);
                paramString += "}";
                $.extend(param, $.parseJSON(paramString));
                return $(this).form('validate');
            }
        },
        success:function (data) {
            var obj = eval('(' + data + ')');
            if (obj.statusCode == '200') {
                rksh.win_rksh.mask('hide');
                $(rksh.win_rksh).window('close');
                $('#grid_rksh').datagrid('reload');
//                $('#layout_rksh').layout('panel', 'center').panel('refresh');
                $.messager.show({title:'提示框', msg:obj.message, timeout:3000, showType:'slide'});
            } else if (obj.statusCode == "300") {
                rksh.win_rksh.mask('hide');
                $.messager.alert('提示', obj.message, 'info');
            } else if (obj.statusCode == "400") {
                rksh.win_rksh.mask('hide');
                $(rksh.win_rksh).window('close');
                $('#grid_rksh').datagrid('reload');
//                $('#layout_rksh').layout('panel', 'center').panel('refresh');
                $.messager.show({title:'提示框', msg:obj.message, timeout:3000, showType:'slide'});

                $.messager.confirm('确认', '此入库单有物资没有完全入库，是否生成补充采购单？', function (r) {
                    if (r) {
                        $.post($.webPath() + '/cggl/cgdgl/bccgd', {"cgd.id":obj.cgdid}, function (bcdata) {
                            var bcObj = eval('(' + bcdata + ')');
                            if (bcObj.statusCode == '200') {
                                $('#grid_rksh').datagrid('reload');
//                                $('#layout_rksh').layout('panel', 'center').panel('refresh');
                                $.messager.alert('提示', bcObj.message, 'info');
                            }
                            else {
                                $.messager.alert('提示', bcObj.message, 'info');
                            }
                        });
                    }
                });
            }
        }
    });
}

//删除附件
function deleteFj(fileId, id) {
    $.messager.confirm('确认', '是否确认删除此附件', function (r) {
        if (r) {
            $.post($.webPath() + '/base/fj/deleteFj', {'fjId': fileId}, function (data) {
                var obj = eval('(' + data + ')');
                if (obj.statusCode == '200') {
                    $("#rksh-file" + fileId).remove();
                    $("#" + id).fadeOut(500, function () {
                        $(this).remove();
                    });
                }
            });
        }
    })
}

